package com.tianye.salon.controller.admin;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tianye.salon.dto.AdminUserFormDto;
import com.tianye.salon.exception.MyException;
import com.tianye.salon.model.AdminUser;
import com.tianye.salon.service.AdminUserService;
import com.tianye.salon.util.CheckUtil;
import com.tianye.salon.util.ConversionMd5;




/**
 * 后台信息 - 密码修改
 * @author zhangyong
 */
@Controller
@RequestMapping("/admin-chpwd")
public class ChpwdController {
	protected Logger logger = LoggerFactory.getLogger(ChpwdController.class);
	@Autowired
	private AdminUserService adminUserService;
	
	@RequestMapping("index")
	public String index(Model model, HttpSession session){
		int uid = Integer.parseInt(session.getAttribute("adminuid").toString());
		AdminUserFormDto userform = adminUserService.selectFormByPrimaryKey(uid);
		userform.setPwd(null);
		model.addAttribute("userform", userform);
		
		return "/admin/chpwd";
	}
	
	@RequestMapping(value="changepass")
	public String changepass(@ModelAttribute("userform") @Valid AdminUserFormDto userform, BindingResult bindingResult, Model model) throws Exception{
		/*if(bindingResult.hasErrors()){
			List<ObjectError> errors = bindingResult.getAllErrors();

			for(ObjectError err:errors){
				logger.info(err.getCode()+" - "+err.getDefaultMessage());
			}
			
			return "/chpwd";
		}*/
		try {
			String pass = userform.getPwd();
			String confirmPass = userform.getConfirmPwd();
			if(CheckUtil.isEmpty(pass)){
				return "/admin/chpwd";
//				throw new MyException("新密码不能为空！");
			}
			if(CheckUtil.isEmpty(confirmPass)){
				return "/admin/chpwd";
//				throw new MyException("确认新密码不能为空！");
			}
			
			if(!pass.equals(confirmPass)){
				throw new MyException("确认新密码错误！");
			}
			
			AdminUser user = userform.toUser();
			user.setPwd(ConversionMd5.toMd5(user.getPwd()));
			
			adminUserService.updateByPrimaryKeySelective(user);
		} catch (MyException e) {
			e.printStackTrace();
			bindingResult.rejectValue("confirmPwd", "userform.confirmPwd", e.getMessage());
			
            return "/admin/chpwd";
		}
		
		return "redirect:/admin-login/logout";
	}
	
}
